package StudyCode.summary.zipfile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CreateZipFileFromDirectoryUsingZipOutputStream {
	public static void main(String args[]) {
		try {
			String zipFile = "zipdemo1.zip";
			String sourceDirectory = "E:/Copy";

			byte[] buffer = new byte[1024];
			FileOutputStream fout = new FileOutputStream(zipFile);

			ZipOutputStream zout = new ZipOutputStream(fout);

			File dir = new File(sourceDirectory);

			if (!dir.isDirectory()) {
				System.out.println(sourceDirectory + " 不是目录i");
			} else {
				File[] files = dir.listFiles();

				for (int i = 0; i < files.length; i++) {
					System.out.println("添加 " + files[i].getName());

					FileInputStream fin = new FileInputStream(files[i]);

					zout.putNextEntry(new ZipEntry(files[i].getName()));

					int length;

					while ((length = fin.read(buffer)) > 0) {
						zout.write(buffer, 0, length);
					}
					zout.closeEntry();

					fin.close();
				}
			}

			zout.close();
			System.out.println("zip 文件创建成功!");
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}
}
